package com.example.config_datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.config_datasource.DatabaseConnectionInfo;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

    @Bean(initMethod = "init", destroyMethod = "close")
    @Primary
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();

        ZkClient zk = new ZkClient(new ZkConnection("192.168.123.137:2181", 200));

        DatabaseConnectionInfo databaseConnectionInfo = zk.readData("/datasource_config/datasource1");

        zk.subscribeDataChanges("/datasource_config/datasource1", new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {
                DatabaseConnectionInfo newDatabaseConnectionInfo = (DatabaseConnectionInfo) data;

                System.out.println("Switch DatasourceConfig to: " + newDatabaseConnectionInfo);

                if (dataSource.isInited()) {
                    dataSource.close();
                    dataSource.restart();
                }

                dataSource.setUrl(newDatabaseConnectionInfo.getUrl());
                dataSource.setUsername(newDatabaseConnectionInfo.getUsername());
                dataSource.setPassword(newDatabaseConnectionInfo.getPassword());
                dataSource.setDriverClassName(newDatabaseConnectionInfo.getDriverName());

                dataSource.init();
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                System.out.println("datasourceConfig: " + dataPath + " deleted ");
            }
        });

        dataSource.setUrl(databaseConnectionInfo.getUrl());
        dataSource.setUsername(databaseConnectionInfo.getUsername());
        dataSource.setPassword(databaseConnectionInfo.getPassword());
        dataSource.setDriverClassName(databaseConnectionInfo.getDriverName());

        return dataSource;
    }
}
